package com.ruoyi.system.service.impl;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.BanknoteSerialNumberPairing;
import com.ruoyi.system.domain.BanknoteSerialNumberRecord;
import com.ruoyi.system.domain.GroupResult;
import com.ruoyi.system.domain.NiceRecord;
import com.ruoyi.system.domain.vo.BanknoteSerialNumberRecordVo;
import com.ruoyi.system.mapper.BanknoteSerialNumberPairingMapper;
import com.ruoyi.system.mapper.BanknoteSerialNumberRecordMapper;
import com.ruoyi.system.service.IBanknoteSerialNumberPairingService;
import com.ruoyi.system.service.INiceRecordService;
import com.ruoyi.system.service.IUserMoneyService;
import com.ruoyi.system.utils.SerialNumberChecker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserMoneyServiceImpl implements IUserMoneyService {

    @Autowired
    private BanknoteSerialNumberRecordMapper banknoteSerialNumberRecordMapper;

    @Autowired
    private IBanknoteSerialNumberPairingService banknoteSerialNumberPairingService;
    @Autowired
    private BanknoteSerialNumberPairingMapper banknoteSerialNumberPairingMapper;
    @Autowired
    private INiceRecordService iNiceRecordService;


    @Transactional
    @Override
    public int insertOne(BanknoteSerialNumberRecord banknoteSerialNumberRecord) {
        //验证号码是否合规
        if (!SerialNumberChecker.isValidNumber(banknoteSerialNumberRecord.getSerialNumber())) {
            throw new ServiceException("抱歉，你输入的号码不符合规则！");
        }
        //验证是否存在相同号码
        if (banknoteSerialNumberRecordMapper.selectOneByTypeAndCode(banknoteSerialNumberRecord.getBillType(), banknoteSerialNumberRecord.getSerialNumber()) != null) {
            throw new ServiceException("抱歉，你输入的号码已存在！");
        }
        banknoteSerialNumberRecord.setCreateTime(new Date());
        banknoteSerialNumberRecord.setCreatorAccount(SecurityUtils.getUsername());
        banknoteSerialNumberRecord.setNumberOwnerAccount(SecurityUtils.getUsername());
        //微信号
        banknoteSerialNumberRecord.setContactWechatId(SecurityUtils.getLoginUser().getUser().getRemark());

        //验证是否为靓号
        if (SerialNumberChecker.isLuckyNumber(banknoteSerialNumberRecord.getSerialNumber())) {
            banknoteSerialNumberRecord.setIsNiceNumber(1L);
            // 新增一个靓号记录
            NiceRecord niceRecord = new NiceRecord(0,banknoteSerialNumberRecord.getBillType(),banknoteSerialNumberRecord.getSerialNumber(),banknoteSerialNumberRecord.getNumberType(),1,banknoteSerialNumberRecord.getNumberOwnerAccount());
            iNiceRecordService.insertNiceRecord(niceRecord);
        }
        // 查找是否有匹配的号码
        Integer type = null;
        if (banknoteSerialNumberRecord.getBillType() == 0){
            type = 1;
        }else {
            type = 0;
        }
        BanknoteSerialNumberRecord data = banknoteSerialNumberRecordMapper.selectOneByTypeAndCode(type, banknoteSerialNumberRecord.getSerialNumber());
        if (data != null){
            //存在配对号码
            List<BanknoteSerialNumberPairing> list = new ArrayList<>();
            BanknoteSerialNumberPairing banknoteSerialNumberPairingOne = new BanknoteSerialNumberPairing(banknoteSerialNumberRecord.getBillType(),banknoteSerialNumberRecord.getSerialNumber(), banknoteSerialNumberRecord.getNumberOwnerAccount());
            BanknoteSerialNumberPairing banknoteSerialNumberPairingTwo = new BanknoteSerialNumberPairing(data.getBillType(),data.getSerialNumber(), data.getNumberOwnerAccount());
            list.add(banknoteSerialNumberPairingOne);
            list.add(banknoteSerialNumberPairingTwo);
            banknoteSerialNumberPairingService.insertList(list);

        }

        return banknoteSerialNumberRecordMapper.insertBanknoteSerialNumberRecord(banknoteSerialNumberRecord);
    }

    /**
     * 新增标十
     * @param banknoteSerialNumberRecords
     * @return
     */
    @Override
    public int insertTen(List<BanknoteSerialNumberRecord> banknoteSerialNumberRecords) {
        if (banknoteSerialNumberRecords.isEmpty()){
            return 0;
        }

        List<String> codes = banknoteSerialNumberRecords.stream().map(BanknoteSerialNumberRecord::getSerialNumber).collect(Collectors.toList());

        //验证是否为标十
        if (!SerialNumberChecker.validateTenNumbers(codes)) {
            throw new ServiceException("抱歉，你输入的这十个号码不符合标十规则！");
        }
        //验证这些号码是否存在
        List<BanknoteSerialNumberRecord> oldList = banknoteSerialNumberRecordMapper.selectByTypeAndCodes(banknoteSerialNumberRecords.get(0).getBillType(), codes);
        //找到存在的
        List<BanknoteSerialNumberRecord> exitRecords = banknoteSerialNumberRecords.stream()
                .filter(newRecord -> oldList.stream()
                        .allMatch(existingRecord -> existingRecord.getSerialNumber().equals(newRecord.getSerialNumber())))
                .collect(Collectors.toList());

        if (!oldList.isEmpty()){
            throw new ServiceException("抱歉，你输入的这些号码中，有已存在的号码:"+ exitRecords.stream().map(BanknoteSerialNumberRecord::getSerialNumber).collect(Collectors.joining(",")));
        }

        //验证这是个号码是否符合靓号规则
        boolean luckyStandardTen = SerialNumberChecker.isLuckyStandardTen(codes);



        banknoteSerialNumberRecords.forEach(item ->{
            item.setCreateTime(new Date());
            item.setCreatorAccount(SecurityUtils.getUsername());
            item.setNumberOwnerAccount(SecurityUtils.getUsername());
            item.setIsNiceNumber(1L);
//            if (luckyStandardTen) {
//                item.setIsNiceNumber(1L);
//            }
            item.setContactWechatId(SecurityUtils.getLoginUser().getUser().getRemark());
        });

        if (true){
            for (BanknoteSerialNumberRecord banknoteSerialNumberRecord : banknoteSerialNumberRecords) {
                // 新增一个靓号记录
                NiceRecord niceRecord = new NiceRecord(0,banknoteSerialNumberRecord.getBillType(),banknoteSerialNumberRecord.getSerialNumber(),banknoteSerialNumberRecord.getNumberType(),10,banknoteSerialNumberRecord.getNumberOwnerAccount());
                iNiceRecordService.insertNiceRecord(niceRecord);
            }
        }
        // 查找是否有匹配的号码
        // 查找是否有匹配的号码
        Integer type = null;
        BanknoteSerialNumberRecord banknoteSerialNumberRecord = banknoteSerialNumberRecords.get(0);
        if (banknoteSerialNumberRecord.getBillType() == 0){
            type = 1;
        }else {
            type = 0;
        }
        List<BanknoteSerialNumberRecord> dateList = banknoteSerialNumberRecordMapper.selectByTypeAndCodes(type, codes);
        //转成map
        Map<String, BanknoteSerialNumberRecord> dataMap = dateList.stream().collect(Collectors.toMap(BanknoteSerialNumberRecord::getSerialNumber, item -> item));
        List<BanknoteSerialNumberPairing> list = new ArrayList<>();
        banknoteSerialNumberRecords.forEach(item ->{
            BanknoteSerialNumberRecord data = dataMap.get(item.getSerialNumber());
            if (data != null){
                //存在配对号码
                BanknoteSerialNumberPairing banknoteSerialNumberPairingOne = new BanknoteSerialNumberPairing(item.getBillType(),item.getSerialNumber(), item.getNumberOwnerAccount());
                BanknoteSerialNumberPairing banknoteSerialNumberPairingTwo = new BanknoteSerialNumberPairing(data.getBillType(),data.getSerialNumber(), data.getNumberOwnerAccount());
                list.add(banknoteSerialNumberPairingOne);
                list.add(banknoteSerialNumberPairingTwo);
            }
        });
        if (!list.isEmpty()){
            banknoteSerialNumberPairingService.insertList(list);
        }

        // 批量新增
        return banknoteSerialNumberRecordMapper.insertList(banknoteSerialNumberRecords);
    }

    @Override
    public int insertTens(List<BanknoteSerialNumberRecord> banknoteSerialNumberRecords) {
        if (banknoteSerialNumberRecords.isEmpty()){
            return 0;
        }
        List<String> codes = banknoteSerialNumberRecords.stream().map(BanknoteSerialNumberRecord::getSerialNumber).collect(Collectors.toList());

        //验证是否为标百
        if (!SerialNumberChecker.validateHundredNumbers(codes)) {
            throw new ServiceException("抱歉，你输入的这百个号码不符合标百规则！");
        }
        //验证这些号码是否存在
        List<BanknoteSerialNumberRecord> oldList = banknoteSerialNumberRecordMapper.selectByTypeAndCodes(banknoteSerialNumberRecords.get(0).getBillType(), codes);
        //找到存在的
        List<BanknoteSerialNumberRecord> exitRecords = banknoteSerialNumberRecords.stream()
                .filter(newRecord -> oldList.stream()
                        .allMatch(existingRecord -> existingRecord.getSerialNumber().equals(newRecord.getSerialNumber())))
                .collect(Collectors.toList());

        if (!oldList.isEmpty()){
            throw new ServiceException("抱歉，你输入的这些号码中，有已存在的号码:"+ exitRecords.stream().map(BanknoteSerialNumberRecord::getSerialNumber).collect(Collectors.joining(",")));
        }
        //验证是否符合靓号
        boolean luckyStandardTens = SerialNumberChecker.isLuckyStandardTens(codes);

        banknoteSerialNumberRecords.forEach(item ->{
            item.setCreateTime(new Date());
            item.setCreatorAccount(SecurityUtils.getUsername());
            item.setNumberOwnerAccount(SecurityUtils.getUsername());
            item.setIsNiceNumber(1L);

//            if (luckyStandardTens) {
//                item.setIsNiceNumber(1L);
//            }else {
//                item.setIsNiceNumber(0L);
//            }
            item.setContactWechatId(SecurityUtils.getLoginUser().getUser().getRemark());
        });
        for (BanknoteSerialNumberRecord banknoteSerialNumberRecord : banknoteSerialNumberRecords) {
            // 新增一个靓号记录
            NiceRecord niceRecord = new NiceRecord(0,banknoteSerialNumberRecord.getBillType(),banknoteSerialNumberRecord.getSerialNumber(),banknoteSerialNumberRecord.getNumberType(),100,banknoteSerialNumberRecord.getNumberOwnerAccount());
            iNiceRecordService.insertNiceRecord(niceRecord);
        }
//        if(luckyStandardTens){
//            for (BanknoteSerialNumberRecord banknoteSerialNumberRecord : banknoteSerialNumberRecords) {
//                // 新增一个靓号记录
//                NiceRecord niceRecord = new NiceRecord(0,banknoteSerialNumberRecord.getBillType(),banknoteSerialNumberRecord.getSerialNumber(),banknoteSerialNumberRecord.getNumberType(),100,banknoteSerialNumberRecord.getNumberOwnerAccount());
//                iNiceRecordService.insertNiceRecord(niceRecord);
//            }
//        }

        // 查找是否有匹配的号码
        // 查找是否有匹配的号码
        Integer type = null;
        BanknoteSerialNumberRecord banknoteSerialNumberRecord = banknoteSerialNumberRecords.get(0);
        if (banknoteSerialNumberRecord.getBillType() == 0){
            type = 1;
        }else {
            type = 0;
        }
        List<BanknoteSerialNumberRecord> dateList = banknoteSerialNumberRecordMapper.selectByTypeAndCodes(type, codes);
        //转成map
        Map<String, BanknoteSerialNumberRecord> dataMap = dateList.stream().collect(Collectors.toMap(BanknoteSerialNumberRecord::getSerialNumber, item -> item));
        List<BanknoteSerialNumberPairing> list = new ArrayList<>();
        banknoteSerialNumberRecords.forEach(item ->{
            BanknoteSerialNumberRecord data = dataMap.get(item.getSerialNumber());
            if (data != null){
                //存在配对号码
                BanknoteSerialNumberPairing banknoteSerialNumberPairingOne = new BanknoteSerialNumberPairing(item.getBillType(),item.getSerialNumber(), item.getNumberOwnerAccount());
                BanknoteSerialNumberPairing banknoteSerialNumberPairingTwo = new BanknoteSerialNumberPairing(data.getBillType(),data.getSerialNumber(), data.getNumberOwnerAccount());
                list.add(banknoteSerialNumberPairingOne);
                list.add(banknoteSerialNumberPairingTwo);
            }
        });
        if (!list.isEmpty()){
            banknoteSerialNumberPairingService.insertList(list);
        }


        // 批量新增
        return banknoteSerialNumberRecordMapper.insertList(banknoteSerialNumberRecords);
    }


    /**
     * 新增连续号
     * @param banknoteSerialNumberRecords
     * @return
     */
    @Override
    public int insertContinuousCodes(List<BanknoteSerialNumberRecord> banknoteSerialNumberRecords) {
        if (banknoteSerialNumberRecords.isEmpty()){
            return 0;
        }
        List<String> codes = banknoteSerialNumberRecords.stream().map(BanknoteSerialNumberRecord::getSerialNumber).collect(Collectors.toList());
        if (!SerialNumberChecker.isConsecutiveNumbers(codes)) {
            throw new ServiceException("抱歉，你输入的这连续号码不符合连续规则！");
        }

        //验证这些号码是否存在
        List<BanknoteSerialNumberRecord> oldList = banknoteSerialNumberRecordMapper.selectByTypeAndCodes(banknoteSerialNumberRecords.get(0).getBillType(), codes);
        //找到存在的
        if (!oldList.isEmpty()){
            List<BanknoteSerialNumberRecord> exitRecords = banknoteSerialNumberRecords.stream()
                    .filter(newRecord -> oldList.stream()
                            .allMatch(existingRecord -> existingRecord.getSerialNumber().equals(newRecord.getSerialNumber())))
                    .collect(Collectors.toList());

            if (!exitRecords.isEmpty()){
                throw new ServiceException("抱歉，你输入的这些号码中，有已存在的号码:"+ exitRecords.stream().map(BanknoteSerialNumberRecord::getSerialNumber).collect(Collectors.joining(",")));
            }
        }

        banknoteSerialNumberRecords.forEach(item ->{
            item.setCreateTime(new Date());
            item.setCreatorAccount(SecurityUtils.getUsername());
            item.setNumberOwnerAccount(SecurityUtils.getUsername());
            item.setContactWechatId(SecurityUtils.getLoginUser().getUser().getRemark());
            if (SerialNumberChecker.isLuckyNumber(item.getSerialNumber())) {
                item.setIsNiceNumber(1L);
            }
        });



        // 查找是否有匹配的号码
        Integer type = null;
        BanknoteSerialNumberRecord banknoteSerialNumberRecord = banknoteSerialNumberRecords.get(0);
        if (banknoteSerialNumberRecord.getBillType() == 0){
            type = 1;
        }else {
            type = 0;
        }
        List<BanknoteSerialNumberRecord> dateList = banknoteSerialNumberRecordMapper.selectByTypeAndCodes(type, codes);
        //转成map
        Map<String, BanknoteSerialNumberRecord> dataMap = dateList.stream().collect(Collectors.toMap(BanknoteSerialNumberRecord::getSerialNumber, item -> item));
        List<BanknoteSerialNumberPairing> list = new ArrayList<>();
        banknoteSerialNumberRecords.forEach(item ->{
            BanknoteSerialNumberRecord data = dataMap.get(item.getSerialNumber());
            if (data != null){
                //存在配对号码
                BanknoteSerialNumberPairing banknoteSerialNumberPairingOne = new BanknoteSerialNumberPairing(item.getBillType(),item.getSerialNumber(), item.getNumberOwnerAccount());
                BanknoteSerialNumberPairing banknoteSerialNumberPairingTwo = new BanknoteSerialNumberPairing(data.getBillType(),data.getSerialNumber(), data.getNumberOwnerAccount());
                list.add(banknoteSerialNumberPairingOne);
                list.add(banknoteSerialNumberPairingTwo);
            }
        });
        if (!list.isEmpty()){
            banknoteSerialNumberPairingService.insertList(list);
        }
        // 批量新增
        return banknoteSerialNumberRecordMapper.insertList(banknoteSerialNumberRecords);
    }

    /**
     * 查询自己的号码库
     * @param record
     * @return
     */
    @Override
    public List<BanknoteSerialNumberRecord> listMy(BanknoteSerialNumberRecord record) {
        if (StringUtils.isNoneBlank(record.getSerialNumber())  && !record.getSerialNumber().contains("J")){
            record.setSerialNumber("J"+record.getSerialNumber());
        }
        if (record.getBillType() != null && record.getBillType() == -1){
            record.setBillType(null);
        }
        if (record.getNumberType() != null && record.getNumberType() == -1){
            record.setNumberType(null);
        }
        record.setNumberOwnerAccount(SecurityUtils.getUsername());
        List<BanknoteSerialNumberRecord> banknoteSerialNumberRecords = banknoteSerialNumberRecordMapper.selectBanknoteSerialNumberRecordList(record);
        //根据项目类别进行分类
        Map<Long,List<BanknoteSerialNumberRecord>> typeMap = banknoteSerialNumberRecords.stream().collect(Collectors.groupingBy(BanknoteSerialNumberRecord::getNumberType));
        List<BanknoteSerialNumberRecord> list = new ArrayList<>();

        //处理单张数据
        List<BanknoteSerialNumberRecord> banknoteSerialNumberRecords1 = typeMap.get(0L);
        if (banknoteSerialNumberRecords1 != null){
            banknoteSerialNumberRecords1.forEach(item ->{
                item.setIds(Collections.singletonList(item.getId()));
            });
            list.addAll(banknoteSerialNumberRecords1);
        }

        //处理标十数据
        //按大小排序
        banknoteSerialNumberRecords.sort(Comparator.comparing(BanknoteSerialNumberRecord::getSerialNumber));
        List<BanknoteSerialNumberRecord> banknoteSerialNumberRecords2 = typeMap.get(1L);
        if (banknoteSerialNumberRecords2 != null){
            //帮我找出每个十相连的数据
            //根据类别分组
            Map<Integer, List<BanknoteSerialNumberRecord>> typeMap1 = banknoteSerialNumberRecords2.stream().collect(Collectors.groupingBy(BanknoteSerialNumberRecord::getBillType));
            typeMap1.forEach((key, value) -> {
                value.sort(Comparator.comparing(BanknoteSerialNumberRecord::getSerialNumber));
                List<GroupResult> groupResults = groupSerialNumbers(value);
                for (GroupResult groupResult : groupResults) {
                    BanknoteSerialNumberRecord firstObject = groupResult.getFirstObject();
                    firstObject.setSerialNumber(groupResult.getGroupedNumber());
                    firstObject.setIds(groupResult.getList().stream().map(BanknoteSerialNumberRecord::getId).collect(Collectors.toList()));

                    list.add(firstObject);
                }
            });

        }

        //处理标百数据
        banknoteSerialNumberRecords.sort(Comparator.comparing(BanknoteSerialNumberRecord::getSerialNumber));
        List<BanknoteSerialNumberRecord> banknoteSerialNumberRecords3 = typeMap.get(2L);
        if (banknoteSerialNumberRecords3 != null){

            //根据类别分组
            Map<Integer, List<BanknoteSerialNumberRecord>> typeMap1 = banknoteSerialNumberRecords3.stream().collect(Collectors.groupingBy(BanknoteSerialNumberRecord::getBillType));
            typeMap1.forEach((key, value) ->{
                value.sort(Comparator.comparing(BanknoteSerialNumberRecord::getSerialNumber));
                List<GroupResult> groupResults = groupSerialNumbersTens(value);
                for (GroupResult groupResult : groupResults) {
                    BanknoteSerialNumberRecord firstObject = groupResult.getFirstObject();
                    firstObject.setSerialNumber(groupResult.getGroupedNumber());
                    firstObject.setIds(groupResult.getList().stream().map(BanknoteSerialNumberRecord::getId).collect(Collectors.toList()));
                    list.add(firstObject);
                }
            });


        }


        List<BanknoteSerialNumberRecord> banknoteSerialNumberRecords4 = typeMap.get(3L);
        if (banknoteSerialNumberRecords4 != null){

            //根据类别分组
            Map<Integer, List<BanknoteSerialNumberRecord>> typeMap1 = banknoteSerialNumberRecords4.stream().collect(Collectors.groupingBy(BanknoteSerialNumberRecord::getBillType));
            typeMap1.forEach((key, value) ->{
                value.sort(Comparator.comparing(BanknoteSerialNumberRecord::getSerialNumber));
                List<GroupResult> groupResults = groupSerialNumberss(value);
                for (GroupResult groupResult : groupResults) {
                    BanknoteSerialNumberRecord firstObject = groupResult.getFirstObject();
                    firstObject.setSerialNumber(groupResult.getGroupedNumber());
                    firstObject.setIds(groupResult.getList().stream().map(BanknoteSerialNumberRecord::getId).collect(Collectors.toList()));

                    list.add(firstObject);
                }
            });


        }


        return list;
    }


    public static List<GroupResult> groupSerialNumbersTens(List<BanknoteSerialNumberRecord> objects) {
        //按照类型分类
        List<GroupResult> groupedResults = new ArrayList<>();

        Map<Integer, List<BanknoteSerialNumberRecord>> typeMap = objects.stream().collect(Collectors.groupingBy(BanknoteSerialNumberRecord::getBillType));
        typeMap.forEach((key, value) -> {
            //value进行排序 每10位 间隔取
            value.sort(Comparator.comparing(BanknoteSerialNumberRecord::getSerialNumber));
            for (int i = 0; i < value.size(); i += 100) {
                int end = Math.min(i + 100, value.size());
                String firstSerialNumber = value.get(i).getSerialNumber();
                String lastSerialNumber = value.get(end - 1).getSerialNumber();
                String newSerialNumber = firstSerialNumber + "-" + lastSerialNumber.substring(lastSerialNumber.length() - 3);
                groupedResults.add(new GroupResult(newSerialNumber, value.get(i),value.subList(i, end)));
            }

        });

        return groupedResults;
    }


    public static List<GroupResult> groupSerialNumberss(List<BanknoteSerialNumberRecord> objects) {
        List<GroupResult> groupedResults = new ArrayList<>();
        if (objects.isEmpty()) {
            return groupedResults;
        }
        int startIndex = 0;
        while (startIndex < objects.size()) {
            int endIndex = startIndex;
            while (endIndex + 1 < objects.size()) {
                String current = objects.get(endIndex).getSerialNumber();
                String next = objects.get(endIndex + 1).getSerialNumber();
                String currentPrefix = current.substring(0, current.length() - 2);
                String nextPrefix = next.substring(0, next.length() - 2);
                int currentSuffix = Integer.parseInt(current.substring(current.length() - 2));
                int nextSuffix = Integer.parseInt(next.substring(next.length() - 2));
                if (!currentPrefix.equals(nextPrefix) || nextSuffix != currentSuffix + 1) {
                    break;
                }
                endIndex++;
            }
            if (endIndex >= startIndex) {
                String start = objects.get(startIndex).getSerialNumber();
                String end = objects.get(endIndex).getSerialNumber();
                String groupedNumber = start + "-" + end.substring(end.length() - 2);
                groupedResults.add(new GroupResult(groupedNumber, objects.get(startIndex), objects.subList(startIndex, endIndex + 1)));
            }
            startIndex = endIndex + 1;
        }
        return groupedResults;
    }
    public static List<GroupResult> groupSerialNumbers(List<BanknoteSerialNumberRecord> objects) {
        //按照类型分类
        List<GroupResult> groupedResults = new ArrayList<>();

        Map<Integer, List<BanknoteSerialNumberRecord>> typeMap = objects.stream().collect(Collectors.groupingBy(BanknoteSerialNumberRecord::getBillType));
        typeMap.forEach((key, value) -> {
            //value进行排序 每10位 间隔取
            value.sort(Comparator.comparing(BanknoteSerialNumberRecord::getSerialNumber));
            for (int i = 0; i < value.size(); i += 10) {
                int end = Math.min(i + 10, value.size());
                String firstSerialNumber = value.get(i).getSerialNumber();
                String lastSerialNumber = value.get(end - 1).getSerialNumber();
                String newSerialNumber = firstSerialNumber + "-" + lastSerialNumber.substring(lastSerialNumber.length() - 2);
                groupedResults.add(new GroupResult(newSerialNumber, value.get(i), value.subList(i, end)));
            }

        });

        return groupedResults;
    }
    @Override
    public int deleteMy(Long[] ids) {
        if (ids.length == 0){
            return 0;
        }
        //校验这些号码是否是自己的
        List<BanknoteSerialNumberRecord> list = banknoteSerialNumberRecordMapper.selectBanknoteSerialNumberRecordByIds(ids,SecurityUtils.getUsername());
        if (!list.isEmpty()){
            throw new ServiceException("抱歉，你输入的这些号码中，有非自己的号码:"+ list.stream().map(BanknoteSerialNumberRecord::getSerialNumber).collect(Collectors.joining(",")));
        }
//        删除这些号码的配对记录
        banknoteSerialNumberPairingService.deleteBanknoteSerialNumberPairingByIds(ids);
        //删除靓号记录
//        iNiceRecordService.deleteNiceRecordByIds(ids);
        return banknoteSerialNumberRecordMapper.deleteBanknoteSerialNumberRecordByIds(ids);
    }

    /**
     * 获取用户自己的靓号
     * @param niceRecord
     * @return
     */
    @Override
    public List<NiceRecord> getMyNiceCodes(NiceRecord niceRecord) {
        niceRecord.setOwner(SecurityUtils.getUsername());
        List<NiceRecord> niceRecords = iNiceRecordService.selectNiceRecordList(niceRecord);
        //根据项目类别进行分类
        Map<Long,List<NiceRecord>> typeMap = niceRecords.stream().collect(Collectors.groupingBy(NiceRecord::getNumberType));
        List<NiceRecord> list = new ArrayList<>();

        //处理单张数据
        List<NiceRecord> banknoteSerialNumberRecords1 = typeMap.get(0L);
        if (banknoteSerialNumberRecords1 != null){
            banknoteSerialNumberRecords1.forEach(data -> {
                data.setIds(Collections.singletonList(data.getId()));
            });
            list.addAll(banknoteSerialNumberRecords1);
        }

        //处理标十数据
        //按大小排序
        niceRecords.sort(Comparator.comparing(NiceRecord::getSerialNumber));
        List<NiceRecord> banknoteSerialNumberRecords2 = typeMap.get(1L);
        if (banknoteSerialNumberRecords2 != null){
            //帮我找出每个十相连的数据
            List<GroupResult> groupResults = groupSerialNumbersN(banknoteSerialNumberRecords2);
            for (GroupResult groupResult : groupResults) {
                NiceRecord firstObject = groupResult.getNiceRecord();
                firstObject.setSerialNumber(groupResult.getGroupedNumber());
                firstObject.setIds(groupResult.getNumberRecords().stream().map(NiceRecord::getId).collect(Collectors.toList()));
                list.add(firstObject);
            }
        }

        //处理标百数据
        niceRecords.sort(Comparator.comparing(NiceRecord::getSerialNumber));
        List<NiceRecord> banknoteSerialNumberRecords3 = typeMap.get(2L);
        if (banknoteSerialNumberRecords3 != null){
            List<GroupResult> groupResults = groupSerialNumbersTensN(banknoteSerialNumberRecords3);
            for (GroupResult groupResult : groupResults) {
                NiceRecord firstObject = groupResult.getNiceRecord();
                firstObject.setSerialNumber(groupResult.getGroupedNumber());
                firstObject.setIds(groupResult.getNumberRecords().stream().map(NiceRecord::getId).collect(Collectors.toList()));

                list.add(firstObject);
            }
        }


        List<NiceRecord> banknoteSerialNumberRecords4 = typeMap.get(3L);
        if (banknoteSerialNumberRecords4 != null){
            List<GroupResult> groupResults = groupSerialNumberssN(banknoteSerialNumberRecords4);
            for (GroupResult groupResult : groupResults) {
                NiceRecord firstObject = groupResult.getNiceRecord();
                firstObject.setSerialNumber(groupResult.getGroupedNumber());
                firstObject.setIds(groupResult.getNumberRecords().stream().map(NiceRecord::getId).collect(Collectors.toList()));

                list.add(firstObject);
            }
        }

        return list;
    }

    public List<GroupResult> groupSerialNumberssN(List<NiceRecord> objects) {
        List<GroupResult> groupedResults = new ArrayList<>();
        if (objects.isEmpty()) {
            return groupedResults;
        }
        int startIndex = 0;
        while (startIndex < objects.size()) {
            int endIndex = startIndex;
            while (endIndex + 1 < objects.size()) {
                String current = objects.get(endIndex).getSerialNumber();
                String next = objects.get(endIndex + 1).getSerialNumber();
                String currentPrefix = current.substring(0, current.length() - 2);
                String nextPrefix = next.substring(0, next.length() - 2);
                int currentSuffix = Integer.parseInt(current.substring(current.length() - 2));
                int nextSuffix = Integer.parseInt(next.substring(next.length() - 2));
                if (!currentPrefix.equals(nextPrefix) || nextSuffix != currentSuffix + 1) {
                    break;
                }
                endIndex++;
            }
            if (endIndex >= startIndex) {
                String start = objects.get(startIndex).getSerialNumber();
                String end = objects.get(endIndex).getSerialNumber();
                String groupedNumber = start + "-" + end.substring(end.length() - 2);
                groupedResults.add(new GroupResult(groupedNumber, objects.get(startIndex), objects.subList(startIndex, endIndex + 1)));
            }
            startIndex = endIndex + 1;
        }
        return groupedResults;
    }

    public List<GroupResult> groupSerialNumbersTensN(List<NiceRecord> banknoteSerialNumberRecords3) {
        //按照类型分类
        List<GroupResult> groupedResults = new ArrayList<>();

        Map<Integer, List<NiceRecord>> typeMap = banknoteSerialNumberRecords3.stream().collect(Collectors.groupingBy(NiceRecord::getBillType));
        typeMap.forEach((key, value) -> {
            //value进行排序 每10位 间隔取
            value.sort(Comparator.comparing(NiceRecord::getSerialNumber));
            for (int i = 0; i < value.size(); i += 100) {
                int end = Math.min(i + 100, value.size());
                String firstSerialNumber = value.get(i).getSerialNumber();
                String lastSerialNumber = value.get(end - 1).getSerialNumber();
                String newSerialNumber = firstSerialNumber + "-" + lastSerialNumber.substring(lastSerialNumber.length() - 3);
                groupedResults.add(new GroupResult(newSerialNumber, value.get(i),value.subList(i, end)));
            }

        });

        return groupedResults;

    }

    public List<GroupResult> groupSerialNumbersN(List<NiceRecord> banknoteSerialNumberRecords2) {
        //按照类型分类
        List<GroupResult> groupedResults = new ArrayList<>();

        Map<Integer, List<NiceRecord>> typeMap = banknoteSerialNumberRecords2.stream().collect(Collectors.groupingBy(NiceRecord::getBillType));
        typeMap.forEach((key, value) -> {
            //value进行排序 每10位 间隔取
            value.sort(Comparator.comparing(NiceRecord::getSerialNumber));
            for (int i = 0; i < value.size(); i += 10) {
                int end = Math.min(i + 10, value.size());
                String firstSerialNumber = value.get(i).getSerialNumber();
                String lastSerialNumber = value.get(end - 1).getSerialNumber();
                String newSerialNumber = firstSerialNumber + "-" + lastSerialNumber.substring(lastSerialNumber.length() - 2);
                groupedResults.add(new GroupResult(newSerialNumber, value.get(i), value.subList(i, end)));
            }
        });
        return groupedResults;
    }

    /**
     * 修改自己的靓号
     * @param niceRecord
     * @return
     */
    @Override
    public int updateMyNiceCord(NiceRecord niceRecord) {
        if (!SecurityUtils.getUsername().equals(niceRecord.getOwner())){
            throw new ServiceException("抱歉，你不能操作不属于你的号码！");
        }

        List<Long> ids = niceRecord.getIds();


        return iNiceRecordService.updateByIds(ids, niceRecord.getStatus(), niceRecord.getPrice());
    }

    @Override
    public List<NiceRecord> getNoMyNiceCodes(NiceRecord niceRecord) {
        niceRecord.setStatus(1);
        List<NiceRecord> niceRecords = iNiceRecordService.selectNiceRecordList(niceRecord);
        //根据项目类别进行分类
        Map<Long,List<NiceRecord>> typeMap = niceRecords.stream().collect(Collectors.groupingBy(NiceRecord::getNumberType));
        List<NiceRecord> list = new ArrayList<>();
        //处理单张数据
        List<NiceRecord> banknoteSerialNumberRecords1 = typeMap.get(0L);
        if (banknoteSerialNumberRecords1 != null){
            list.addAll(banknoteSerialNumberRecords1);
        }

        //处理标十数据
        //按大小排序
        niceRecords.sort(Comparator.comparing(NiceRecord::getSerialNumber));
        List<NiceRecord> banknoteSerialNumberRecords2 = typeMap.get(1L);
        if (banknoteSerialNumberRecords2 != null){
            //帮我找出每个十相连的数据
            List<GroupResult> groupResults = groupSerialNumbersN(banknoteSerialNumberRecords2);
            for (GroupResult groupResult : groupResults) {
                NiceRecord firstObject = groupResult.getNiceRecord();
                firstObject.setSerialNumber(groupResult.getGroupedNumber());
                list.add(firstObject);
            }
        }

        //处理标百数据
        niceRecords.sort(Comparator.comparing(NiceRecord::getSerialNumber));
        List<NiceRecord> banknoteSerialNumberRecords3 = typeMap.get(2L);
        if (banknoteSerialNumberRecords3 != null){
            List<GroupResult> groupResults = groupSerialNumbersTensN(banknoteSerialNumberRecords3);
            for (GroupResult groupResult : groupResults) {
                NiceRecord firstObject = groupResult.getNiceRecord();
                firstObject.setSerialNumber(groupResult.getGroupedNumber());
                list.add(firstObject);
            }
        }


        List<NiceRecord> banknoteSerialNumberRecords4 = typeMap.get(3L);
        if (banknoteSerialNumberRecords4 != null){
            List<GroupResult> groupResults = groupSerialNumberssN(banknoteSerialNumberRecords4);
            for (GroupResult groupResult : groupResults) {
                NiceRecord firstObject = groupResult.getNiceRecord();
                firstObject.setSerialNumber(groupResult.getGroupedNumber());
                list.add(firstObject);
            }
        }

        return list;
    }

    /**
     * 获取配号记录
     * @return
     */
    @Override
    public List<BanknoteSerialNumberRecord> getMatching() {

        BanknoteSerialNumberPairing banknoteSerialNumberPairing = new BanknoteSerialNumberPairing();
        banknoteSerialNumberPairing.setOwner(SecurityUtils.getUsername());
        //获取我的配号
        List<BanknoteSerialNumberPairing> list = banknoteSerialNumberPairingMapper.selectBanknoteSerialNumberPairingList(banknoteSerialNumberPairing);
        //获取这些号码
        if (list.isEmpty()){
            return Collections.emptyList();
        }
        //根据billtye分类
        Map<Integer, List<BanknoteSerialNumberPairing>> map = list.stream().collect(Collectors.groupingBy(BanknoteSerialNumberPairing::getBillType));
        //获取对应的匹配号码
        List<BanknoteSerialNumberRecord> myRecords = new ArrayList<>();
        List<BanknoteSerialNumberRecord> otherRecords = new ArrayList<>();

        map.forEach((key,value)->{
            //获取value的号码列表
            List<String> codes = value.stream().map(BanknoteSerialNumberPairing::getSerialNumber).collect(Collectors.toList());

            //获取我自己的号码
            myRecords.addAll( banknoteSerialNumberRecordMapper.selectByTypeAndCodes(key, codes));

            //获取对方的
            if (key == 0){
                otherRecords.addAll(banknoteSerialNumberRecordMapper.selectByTypeAndCodes(1, codes));
            }else {
                otherRecords.addAll(banknoteSerialNumberRecordMapper.selectByTypeAndCodes(0, codes));
            }
        });


        //myRecords根据号码 分组 list
        Map<String, List<BanknoteSerialNumberRecord>> myRecordsMap = myRecords.stream().collect(Collectors.groupingBy(BanknoteSerialNumberRecord::getSerialNumber));
        Map<String, List<BanknoteSerialNumberRecord>> otherRecordsMap = otherRecords.stream().collect(Collectors.groupingBy(BanknoteSerialNumberRecord::getSerialNumber));
        myRecordsMap.forEach((key,value)->{
            List<BanknoteSerialNumberPairing> collect = list.stream().filter(item -> item.getSerialNumber().equals(key)).collect(Collectors.toList());
            Date peiTime = new Date();
            if (!collect.isEmpty()){
                peiTime = collect.get(0).getPeiTime();
            }
            if (otherRecordsMap.containsKey(key)){
                if (value.size() == 1){
                    BanknoteSerialNumberRecord otherRecord = otherRecordsMap.get(key).get(0);
                    value.get(0).setOtherOwner(otherRecord.getNumberOwnerAccount());
                    value.get(0).setOtherBillType(otherRecord.getBillType());
                    value.get(0).setOtherNumberType(otherRecord.getNumberType());
                    value.get(0).setOtherGradedScore(otherRecord.getGradedScore());
                    value.get(0).setOtherNakedOrGraded(otherRecord.getNakedOrGraded());
                    value.get(0).setPeiTime(peiTime);
                }else {
                    List<BanknoteSerialNumberRecord> otherRecordList = otherRecordsMap.get(key);
                    BanknoteSerialNumberRecord otherRecord = new BanknoteSerialNumberRecord();
                    //找到类型不一样的
                    if (value.get(0).getBillType() == 1){
                        //找打相反的
                        otherRecord = otherRecordList.stream().filter(item -> item.getBillType() == 0).findFirst().get();
                    }else {
                        otherRecord = otherRecordList.stream().filter(item -> item.getBillType() == 1).findFirst().get();
                    }


                    value.get(0).setOtherOwner(otherRecord.getNumberOwnerAccount());
                    value.get(0).setOtherBillType(otherRecord.getBillType());
                    value.get(0).setOtherNumberType(otherRecord.getNumberType());
                    value.get(0).setOtherGradedScore(otherRecord.getGradedScore());
                    value.get(0).setOtherNakedOrGraded(otherRecord.getNakedOrGraded());
                    value.get(0).setPeiTime(peiTime);


                    BanknoteSerialNumberRecord otherRecord1 = new BanknoteSerialNumberRecord();
                    //找到类型不一样的
                    if (value.get(1).getBillType() == 1){
                        //找打相反的
                        otherRecord1 = otherRecordList.stream().filter(item -> item.getBillType() == 0).findFirst().get();
                    }else {
                        otherRecord1 = otherRecordList.stream().filter(item -> item.getBillType() == 1).findFirst().get();
                    }
                    value.get(1).setOtherOwner(otherRecord1.getNumberOwnerAccount());
                    value.get(1).setOtherBillType(otherRecord1.getBillType());
                    value.get(1).setOtherNumberType(otherRecord1.getNumberType());
                    value.get(1).setOtherGradedScore(otherRecord1.getGradedScore());
                    value.get(1).setOtherNakedOrGraded(otherRecord1.getNakedOrGraded());
                    value.get(1).setPeiTime(peiTime);
                }



            }
        });


        //myRecordsMap获取list
        List<BanknoteSerialNumberRecord> returnList = new ArrayList<>();
        myRecordsMap.forEach((key,value)->{
            returnList.addAll(value);
        });

        //过滤掉otherOwner为空的
        returnList.removeIf(item->{
            return item.getOtherOwner() == null;
        });
        //根据项目类别进行分类
        Map<Long,List<BanknoteSerialNumberRecord>> typeMap = returnList.stream().collect(Collectors.groupingBy(BanknoteSerialNumberRecord::getNumberType));
        List<BanknoteSerialNumberRecord> listAll = new ArrayList<>();

        //处理单张数据
        List<BanknoteSerialNumberRecord> banknoteSerialNumberRecords1 = typeMap.get(0L);
        if (banknoteSerialNumberRecords1 != null){
            listAll.addAll(banknoteSerialNumberRecords1);
        }

        //处理标十数据
        //按大小排序
        returnList.sort(Comparator.comparing(BanknoteSerialNumberRecord::getSerialNumber));
        List<BanknoteSerialNumberRecord> banknoteSerialNumberRecords2 = typeMap.get(1L);
        if (banknoteSerialNumberRecords2 != null){
            //帮我找出每个十相连的数据
            //根据类别分组
            Map<Integer, List<BanknoteSerialNumberRecord>> typeMap1 = banknoteSerialNumberRecords2.stream().collect(Collectors.groupingBy(BanknoteSerialNumberRecord::getBillType));
            typeMap1.forEach((key,value)->{
                //排序
                value.sort(Comparator.comparing(BanknoteSerialNumberRecord::getSerialNumber));
                List<GroupResult> groupResults = groupSerialNumbers(value);
                for (GroupResult groupResult : groupResults) {
                    BanknoteSerialNumberRecord firstObject = groupResult.getFirstObject();
                    firstObject.setSerialNumber(groupResult.getGroupedNumber());
                    firstObject.setIds(groupResult.getList().stream().map(BanknoteSerialNumberRecord::getId).collect(Collectors.toList()));

                    listAll.add(firstObject);
                }
            });

        }

        //处理标百数据
        returnList.sort(Comparator.comparing(BanknoteSerialNumberRecord::getSerialNumber));
        List<BanknoteSerialNumberRecord> banknoteSerialNumberRecords3 = typeMap.get(2L);
        if (banknoteSerialNumberRecords3 != null){
            Map<Integer, List<BanknoteSerialNumberRecord>> typeMap1 = banknoteSerialNumberRecords3.stream().collect(Collectors.groupingBy(BanknoteSerialNumberRecord::getBillType));
            typeMap1.forEach((key,value)->{
                value.sort(Comparator.comparing(BanknoteSerialNumberRecord::getSerialNumber));
                List<GroupResult> groupResults = groupSerialNumbersTens(value);
                for (GroupResult groupResult : groupResults) {
                    BanknoteSerialNumberRecord firstObject = groupResult.getFirstObject();
                    firstObject.setSerialNumber(groupResult.getGroupedNumber());
                    firstObject.setIds(groupResult.getList().stream().map(BanknoteSerialNumberRecord::getId).collect(Collectors.toList()));
                    listAll.add(firstObject);
                }
            });

        }


        List<BanknoteSerialNumberRecord> banknoteSerialNumberRecords4 = typeMap.get(3L);
        if (banknoteSerialNumberRecords4 != null){
            Map<Integer, List<BanknoteSerialNumberRecord>> typeMap1 = banknoteSerialNumberRecords4.stream().collect(Collectors.groupingBy(BanknoteSerialNumberRecord::getBillType));
            typeMap1.forEach((key,value)->{
                value.sort(Comparator.comparing(BanknoteSerialNumberRecord::getSerialNumber));
                List<GroupResult> groupResults = groupSerialNumberss(value);
                for (GroupResult groupResult : groupResults) {
                    BanknoteSerialNumberRecord firstObject = groupResult.getFirstObject();
                    firstObject.setSerialNumber(groupResult.getGroupedNumber());
                    firstObject.setIds(groupResult.getList().stream().map(BanknoteSerialNumberRecord::getId).collect(Collectors.toList()));

                    listAll.add(firstObject);
                }
            });




        }

        return listAll;
    }
}
